import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import threading
from urllib.parse import urlparse, parse_qs
import urllib.parse

# 全局变量，用于存储 bid
bid = None
# 定义要监测的目录
root_dir = None
# 初始化之前的数量
previous_count = 0


def process_change():
    global root_dir
    print(root_dir)
    print("目录内容数量发生了变化，开始处理...")
    time.sleep(5)
    # 在这里添加你需要执行的操作
    # 例如获取文件夹数量
    folders = [d for d in os.listdir(root_dir) if
               os.path.isdir(os.path.join(root_dir, d)) and d.startswith('exp')]
    folder_count = len(folders)
    print(f"文件夹数量: {folder_count}")

    # 构建视频文件路径
    if folder_count == 1:
        video_path = f'{root_dir}/exp/0.mp4'
        video_path_new = f'{root_dir}/exp/output0.mp4'
    else:
        video_path = f'{root_dir}/exp{folder_count}/0.mp4'
        video_path_new = f'{root_dir}/exp{folder_count}/output0.mp4'

    if os.path.exists(video_path):
        print(f"发现视频文件 {video_path}，开始处理...")
        # 执行 ffmpeg 命令进行视频处理
        command = f'./ffmpeg -i {video_path} -c:v libx264 -crf 23 -preset medium -c:a aac -b:a 128k {video_path_new}'
        try:
            return_code = os.system(command)
            print(f"命令执行返回码: {return_code}")
        except Exception as e:
            print(f"执行命令时出错: {e}")
    else:
        print(f"视频文件 {video_path} 不存在，无法处理。")


def monitor_directory():
    global previous_count, root_dir
    print(previous_count)
    print(root_dir)
    while True:
        if root_dir is None:
            time.sleep(1)
            continue
        try:
            # 获取当前目录内容的数量
            current_count = len(os.listdir(root_dir))
            print(current_count)
            # 检查数量是否发生变化
            if current_count != previous_count:
                process_change()
                # 更新之前的数量
                previous_count = current_count
        except FileNotFoundError:
            print(f"目录 {root_dir} 不存在，等待重新设置...")
            # 每隔一段时间检查一次
        time.sleep(1)


class MyHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        global bid, root_dir, previous_count
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        post_params = parse_qs(post_data.decode('utf-8'))

        if 'bid' in post_params:
            bid = post_params['bid'][0]
            root_dir = f'/Users/dealthknight/Downloads/yolov5-master/runs/{bid}'
            try:
                previous_count = len(os.listdir(root_dir))
                self.send_response(200)
                self.send_header('Content-type', 'text/plain')
                self.end_headers()
                response = f"Received bid: {bid}, monitoring directory: {root_dir}"
                self.wfile.write(response.encode())
            except FileNotFoundError:
                self.send_response(404)
                self.send_header('Content-type', 'text/plain')
                self.end_headers()
                response = f"Directory for bid {bid} not found."
                self.wfile.write(response.encode())
        else:
            self.send_response(400)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            response = "Missing 'bid' parameter in the request."
            self.wfile.write(response.encode())

    def do_GET(self):
        global bid, root_dir, previous_count
        parsed_url = urlparse(self.path)

        if parsed_url.path.startswith('/runs/'):
            # 提取 bid
            parts = parsed_url.path.split('/')
            if len(parts) >= 3:
                bid = parts[2]
                root_dir = f'/Users/dealthknight/Downloads/yolov5-master/runs/{bid}'
                try:
                    # 构建文件路径
                    relative_path = parsed_url.path[len(f'/runs/{bid}'):]
                    if relative_path.startswith('/'):
                        relative_path = relative_path[1:]
                    file_path = os.path.join(root_dir, relative_path)

                    if os.path.isfile(file_path):
                        # 读取文件内容
                        with open(file_path, 'rb') as file:
                            self.send_response(200)
                            self.send_header('Content-type', self.guess_type(file_path))
                            self.end_headers()
                            self.wfile.write(file.read())
                    elif os.path.isdir(file_path):
                        # 列出目录内容
                        file_list = os.listdir(file_path)
                        response = '<html><body><ul>'
                        for file in file_list:
                            response += f'<li><a href="{parsed_url.path}/{file}">{file}</a></li>'
                        response += '</ul></body></html>'
                        self.send_response(200)
                        self.send_header('Content-type', 'text/html')
                        self.end_headers()
                        self.wfile.write(response.encode())
                    else:
                        self.send_response(404)
                        self.send_header('Content-type', 'text/plain')
                        self.end_headers()
                        response = f"File or directory not found: {file_path}"
                        self.wfile.write(response.encode())
                except FileNotFoundError:
                    self.send_response(404)
                    self.send_header('Content-type', 'text/plain')
                    self.end_headers()
                    response = f"Directory for bid {bid} not found."
                    self.wfile.write(response.encode())
            else:
                self.send_response(400)
                self.send_header('Content-type', 'text/plain')
                self.end_headers()
                response = "Invalid request path, missing bid."
                self.wfile.write(response.encode())
        else:
            self.send_response(400)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            response = "Invalid request path."
            self.wfile.write(response.encode())

    def guess_type(self, path):
        if path.endswith('.html'):
            return 'text/html'
        elif path.endswith('.css'):
            return 'text/css'
        elif path.endswith('.js'):
            return 'application/javascript'
        elif path.endswith('.jpg') or path.endswith('.jpeg'):
            return 'image/jpeg'
        elif path.endswith('.png'):
            return 'image/png'
        elif path.endswith('.mp4'):
            return 'video/mp4'
        else:
            return 'application/octet-stream'


def start_http_server():
    PORT = 8000
    with HTTPServer(("", PORT), MyHTTPRequestHandler) as httpd:
        print(f"Serving at port {PORT}")
        httpd.serve_forever()


if __name__ == "__main__":
    # 启动目录监测线程
    monitor_thread = threading.Thread(target=monitor_directory)
    monitor_thread.start()

    # 启动 HTTP 服务线程
    server_thread = threading.Thread(target=start_http_server)
    server_thread.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序终止")